package com.ssy.lingxi.settle.accounts.utils;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.component.redis.service.IRedisUtils;
import com.ssy.lingxi.settle.accounts.service.IPlatformCouponSettlementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 定时任务
 * @author 彭冬冬
 * @version 2.0.0
 * @date 2022/1/25 11:35
 */
@Component
@EnableAsync
public class Scheduler {
    private static final Logger logger = LoggerFactory.getLogger(Scheduler.class);

    @Resource
    private IRedisUtils redisUtils;

    @Resource
    private IPlatformCouponSettlementService platformCouponSettlementService;

    @Async
    @Scheduled(cron = "0 20 00 ? * *")
    @Transactional(rollbackFor = Exception.class)
    public void ScheduledTask() {
        String key = Constants.SETTLE_ACCOUNT_TASK_KEY;
        // 检查定时服务是否正在执行，如正在执行则退出任务
        Object obj = redisUtils.get(key, Constants.REDIS_SETTLEMENT_INDEX);
        if (obj != null) {
            Boolean isExecute = (Boolean) obj;
            if (isExecute) {
                logger.info("定时任务正在执行...");
                return;
            }
        }
        // 设置定时任务正在执行
        redisUtils.set(key, true,10*60L, Constants.REDIS_SETTLEMENT_INDEX);
        try {
            platformCouponSettlementService.timingSettlement(LocalDateTime.now());
        } catch (Exception e) {
            logger.info("平台优惠券结算定时任务失败：{}", e.getMessage());
        }
    }
}
